package com.sfddata.musicpillow.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.sfddata.musicpillow.user.entity.*;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sfddata.musicpillow.common.utils.PageUtils;
import com.sfddata.musicpillow.common.utils.Query;

import com.sfddata.musicpillow.user.dao.TbSleepRecordDao;
import com.sfddata.musicpillow.user.service.TbSleepRecordService;


@Service("tbSleepRecordService")
public class TbSleepRecordServiceImpl extends ServiceImpl<TbSleepRecordDao, TbSleepRecordEntity> implements TbSleepRecordService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TbSleepRecordEntity> page = this.page(
                new Query<TbSleepRecordEntity>().getPage(params),
                new QueryWrapper<TbSleepRecordEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public Long saveByVo(SleepRecordEntityVo sleepRecordEntityVo) {


        TbSleepRecordEntity entity = loadData(sleepRecordEntityVo);
        QueryWrapper<TbSleepRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("col_user_id", entity.getColUserId());
        queryWrapper.eq("col_date", entity.getColDate());
        TbSleepRecordEntity sleepRecordEntity = baseMapper.selectOne(queryWrapper);
        if (sleepRecordEntity == null){
            baseMapper.insert(entity);
            System.out.println("添加新数据"+entity.getId());
        }else {
            entity.setId(sleepRecordEntity.getId());
            baseMapper.updateById(entity);
            System.out.println("更新老数据"+sleepRecordEntity.getId());
            return sleepRecordEntity.getId();
        }
        return entity.getId();
    }

    /**
     * 用数据库记录比对
     * @param entity
     * @return
     * @throws ParseException
     */
    @Override
    public CompareEntity compareRecord(TbSleepRecordEntity entity) throws ParseException {

        CompareEntity compareEntity = new CompareEntity();
        Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(entity.getColDate());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(parse);

        TbSleepRecordEntity yesterdayRecord = this.getRecordByUId(entity.getColUserId() ,entity.getColDate(), 0);
        if (yesterdayRecord != null){

            compareEntity.setDeepCompare(Float.parseFloat(entity.getColDeepDuration()) - Float.parseFloat(yesterdayRecord.getColDeepDuration()));
            compareEntity.setSleepTime((Float.parseFloat(entity.getColSleepDuration()) - Float.parseFloat(yesterdayRecord.getColSleepDuration())));
            compareEntity.setScoreCompare(Float.parseFloat(entity.getColScore()) - Float.parseFloat(yesterdayRecord.getColScore()));
        }else {
            // 这是第一条数据
            return null;
        }
        // 不存在前一天的数据 返回一个空的entity
        return compareEntity;
    }

    /**
     * 获取上一次的睡眠记录,提供给首页
     * @param userId
     * @return
     */
    @Override
    public RecordForIndexEntity getRecordForIndex(Long userId, String time) throws ParseException {

        RecordForIndexEntity entity = new RecordForIndexEntity();
        // 上一次的报告
        TbSleepRecordEntity record = this.getRecordByUId(userId.toString() ,time, 0);
        // 上上次的报告
        String lastTime = LocalDateTime.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        TbSleepRecordEntity lastRecord = this.getRecordByUId(userId.toString(), lastTime, 0);


        // 现在的时间
        if (record != null){
            // 睡眠时长
            entity.setLastSleepingTime( record.getColSleepDuration() );
            // 入睡时间 = 在床时间 - 睡眠时长 = 清醒时间
            entity.setLastFallAsleepTime( record.getColAwakeDuration() );
        }

        if (lastRecord != null && record != null){
            entity.setCompareSleeping(Float.parseFloat(record.getColSleepDuration()) - Float.parseFloat(lastRecord.getColSleepDuration()));

            entity.setCompareFallAsleep(Float.parseFloat(record.getColAwakeDuration()) - Float.parseFloat(lastRecord.getColAwakeDuration()));

        }

        return entity;
    }

    /**
     * 计算并获取Date这一周的记录
     *
     * @param userId
     * @param date
     * @return
     */
    @Override
    public ArrayList<TbSleepRecordEntity> getWeekRecordBeginDate(Long userId, DateVo date) throws ParseException {

        Date firstDay = date.getFirstDay();

        QueryWrapper<TbSleepRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("col_date", DateFormatUtils.format(firstDay, "yyyy-MM-dd"));
        queryWrapper.le("col_date", DateFormatUtils.format(date.getLastDay(), "yyyy-MM-dd"));
        queryWrapper.eq("col_user_id", userId);
        queryWrapper.orderByAsc("col_date"); // 升序

        List<TbSleepRecordEntity> sleepRecordList = baseMapper.selectList(queryWrapper);


        // 试用google的工具类转化
        ArrayList<TbSleepRecordEntity> lists = Lists.newArrayList(sleepRecordList);

        // 修改出0数据 方便显示
        Long day = (date.getLastDay().getTime()-date.getFirstDay().getTime())/24/60/60/1000 + 1;
        System.out.println("天数" + day);
        if (sleepRecordList.size() < 4 || sleepRecordList.size() < 7 && day > 7){
            return null;
        }
        ArrayList<TbSleepRecordEntity> finalList = new ArrayList<>();
        int j = 0; // j对应lists的索引
        Date countDate = firstDay;
        for (int i = 0; i < day; i++) {
            // i对应finalList的索引
            if (j >= lists.size()){
                finalList.add(new TbSleepRecordEntity());
                continue;
            }
            if ((new SimpleDateFormat("yyyy-MM-dd").parse(lists.get(j).getColDate()).getTime() - countDate.getTime()) == 0){
                countDate = new Date(countDate.getTime() + (1000 * 60 * 60 * 24));
                finalList.add(lists.get(j));
                j++;
                continue;
            }

            countDate = new Date(countDate.getTime() + (1000 * 60 * 60 * 24));
            String format = new SimpleDateFormat("yyyy-MM-dd").format(countDate);
            finalList.add(new TbSleepRecordEntity(format));
        }
        return finalList;
    }

    @Override
    public TbSleepRecordEntityVo convertDate(TbSleepRecordEntity sleepRecord) {

        TbSleepRecordEntityVo tbSleepRecordEntityVo = new TbSleepRecordEntityVo();
        BeanUtils.copyProperties(sleepRecord, tbSleepRecordEntityVo);

        String substring = sleepRecord.getColAudioData().substring(1, sleepRecord.getColAudioData().length() - 1);
        String[] split = substring.split(", ");
        List<String> AudioList = Arrays.stream(split).collect(Collectors.toList());
        tbSleepRecordEntityVo.setColAudioData(AudioList);

        String substring1 = sleepRecord.getSleepState().substring(1, sleepRecord.getSleepState().length() - 1);
        String[] split1 = substring1.split(", ");
        List<String> sleepStateList = Arrays.stream(split1).collect(Collectors.toList());
        tbSleepRecordEntityVo.setSleepState(sleepStateList);

        String sleepCurve = sleepRecord.getSleepCurve();
        String curve1 = sleepCurve.replaceAll("Curve", "");
        String x = curve1.replaceAll("x", "\"x\"");
        String y = x.replaceAll("y", "\"y\"");
        String s1 = y.replaceAll("=", ":");
        List<Curve> curveList = JSONArray.parseArray(s1, Curve.class);
        tbSleepRecordEntityVo.setSleepCurve(curveList);

        String substring2 = sleepRecord.getApneaList().substring(1, sleepRecord.getApneaList().length() - 1);
        String[] split2 = substring2.split(", ");
        List<String> apneaList = Arrays.stream(split2).collect(Collectors.toList());
        tbSleepRecordEntityVo.setApneaList(apneaList);

        String substring3 = sleepRecord.getDbList().substring(1, sleepRecord.getDbList().length() - 1);
        String[] split3 = substring3.split(", ");
        List<String> Dblist = Arrays.stream(split3).collect(Collectors.toList());
        tbSleepRecordEntityVo.setDbList(Dblist);

        return tbSleepRecordEntityVo;
    }

    @Override
    public ArrayList<String> getIsReadList(Long userId) {

        QueryWrapper<TbSleepRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_read", 1);
        queryWrapper.eq("col_user_id", userId);
        List<TbSleepRecordEntity> list = this.list(queryWrapper);
        ArrayList<String> datelist = new ArrayList<>();
        if (list.size() > 0){
            for (TbSleepRecordEntity entity : list) {
                datelist.add(entity.getColDate());
            }
        }
        return datelist;
    }

    /**
     * 用上传数据比对
     * @param vo
     * @return
     * @throws ParseException
     */
    @Override
    public CompareEntity compareRecord(SleepRecordEntityVo vo) throws ParseException {


        CompareEntity compareEntity = new CompareEntity();
        Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(vo.getDate());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(parse);

        TbSleepRecordEntity yesterdayRecord = this.getRecordByUId(vo.getUserId() ,vo.getDate(), 0);
        if (yesterdayRecord != null){

            compareEntity.setDeepCompare(Float.parseFloat(vo.getDeepSleep()) - Float.parseFloat(yesterdayRecord.getColDeepDuration()));
            compareEntity.setSleepTime((Float.parseFloat(vo.getSleepTime()) - Float.parseFloat(yesterdayRecord.getColSleepDuration())));
            compareEntity.setScoreCompare(Float.parseFloat(vo.getSleepScore()) - Float.parseFloat(yesterdayRecord.getColScore()));
        }else {
            // 这是第一条数据

        }
        // 不存在前一天的数据 返回一个空的entity
        return compareEntity;
    }

    @Override
    public ArrayList<String> getByUserId(Long userId) {

        QueryWrapper<TbSleepRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("col_user_id", userId);
        queryWrapper.eq("is_read", 0);
        List<TbSleepRecordEntity> tbSleepRecordEntities = baseMapper.selectList(queryWrapper);
        ArrayList<String> datelist = new ArrayList<>();
        if (tbSleepRecordEntities.size() > 0){
            for (TbSleepRecordEntity entity : tbSleepRecordEntities) {
                datelist.add(entity.getColDate());
            }
        }

        return datelist;

    }


    /**
     * 查询最新的
     * @param userId
     * @param date
     * @return
     */
    private TbSleepRecordEntity getRecordByUId(String userId, String date, Integer type) {

        QueryWrapper<TbSleepRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("col_user_id", userId);
        queryWrapper.lt("col_date", date);
        queryWrapper.orderByDesc("col_date");

        TbSleepRecordEntity sleepRecordEntity = null;
        List<TbSleepRecordEntity> tbSleepRecordEntities = baseMapper.selectList(queryWrapper);
        // 如果没有记录 返回空
        // 有一条记录 对比箭头是空
        // 有两条以上的记录才有对比
        if ( tbSleepRecordEntities.size() > 0){
            sleepRecordEntity = tbSleepRecordEntities.get(0);
        }
        return sleepRecordEntity;
    }

    private TbSleepRecordEntity loadData(SleepRecordEntityVo vo) {

        String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        // 上床打开app的时
        Date bedDate = new Date(Long.parseLong(vo.getGoToBedTime()));
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(bedDate);
        Date date = new Date(Long.parseLong(vo.getGoToBedTime()) / (1000*3600*24)*(1000*3600*24)- TimeZone.getDefault().getRawOffset() + 24*60*60*1000 +7200*1000);
        String sleepDate = countDate(vo.getGoToBedTime());


        TbSleepRecordEntity entity = new TbSleepRecordEntity();


        TbSleepRecordEntity tbSleepRecordEntity = new TbSleepRecordEntity(
                vo.getUserId(),
                vo.getGoToBedTime(),
                vo.getGetUpTime(),
                vo.getFellAsleep(),
                vo.getDate(), // 睡觉的时间 2点算前一天
                vo.getSleepScore(),
                vo.getSleepTime(),
                vo.getBedTime(),
                vo.getDeepSleep(),
                vo.getShallowSleep(),
                vo.getWakingTime(),
                new ArrayList<>().toString(), // todo 音频检测数据
                "0", // todo 异常数据
                vo.getDbList().stream().filter( s -> s!="0" ).collect(Collectors.toList()).size(), // 打鼾次数
                vo.getApneaList().stream().filter( s -> s!="0" ).collect(Collectors.toList()).size(), // 呼吸暂停次数

                vo.getSnoreInterveneCount(),
                vo.getSnoreInterveneSuccessCount(),
                "Asia/Shanghai",

                vo.getLatencyOfSleep(),
                vo.getSleepState(),
                vo.getSleepCurve(),
                vo.getApneaList(),
                vo.getDbList(),
                vo.getSnoreTime()
        );

        System.out.println("dataLoad成功");

        return tbSleepRecordEntity;
    }

    // 计算睡眠时间，凌晨2点之前 算做一天
    private String countDate(String goToBedTime) {

        return null;
    }

}